<template>
    <div class="app-container">
        <el-row>
            <el-col :span=" 24 " class="card-box">
                <el-card>
                    <searchForm
                        @init=" init "
                        :searchData=" searchData "
                        :searchItem=" searchItem "
                    ></searchForm>
                </el-card>
            </el-col>
            <el-col :span=" 24 " class="card-box">
                <el-card>
                    <template #header>
                        <el-button type="primary" size="small" @click="confirmAdd()">添加</el-button>
                    </template>
                    <my-table
                        :columns=" columns "
                        :showIndex=" true "
                        :data=" tableData "
                        :loading=" table_loading "
                        :pagination=" pagination "
                        :cellStyle=" { padding: '6px 0' } "
                        @currentChange=" currentChange "
                        @handleSizeChange=" handleSizeChange "
                    >
                        <template #coverPic=" slotProps ">
                            <el-image
                                style="width: 100px; height: 100px"
                                :src="slotProps.callback.row.coverPic"
                                fit="cover"
                            />
                        </template>
                        <template #state=" slotProps ">
                            <div> {{ slotProps.callback.row.state==0?'已下架':'已上架' }} </div>
                        </template>
                        <template #operation=" slotProps ">
                            <el-button
                                link
                                type="primary"
                                size="small"
                                @click="handleEdit(slotProps.callback.row)"
                            >修改</el-button>
                            <el-button
                                link
                                type="primary"
                                size="small"
                                @click="handleUpdateState(slotProps.callback.row)"
                            >{{slotProps.callback.row.state==1?'下架':'上架'}}</el-button>
                            <el-popconfirm
                                title="确认删除？"
                                @confirm="handleDelete(slotProps.callback.row.id)"
                            >
                                <template #reference>
                                    <el-button link type="warning" size="small">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </template>
                    </my-table>
                </el-card>
                <el-dialog
                    :title=" dialogForm.title "
                    v-model=" dialogForm.dialogVisible "
                    :destroy-on-close=" true "
                    :close-on-press-escape="false"
                    :close-on-click-modal=" false "
                    top="5%"
                    width="60%"
                >
                    <div>
                        <form-page
                            v-model:refObj=" formInfo.formRef "
                            :data=" formInfo.data "
                            :field-list=" formInfo.fieldList "
                            :rules=" formInfo.rules "
                            :label-width=" formInfo.labelWidth "
                            :list-type-info=" listTypeInfo "
                        >
                            <template v-slot:form-item-coverPic>
                                <imgUpload
                                    ref="upload"
                                    :imgSrc="data.coverPic"
                                    @uploadSuccess="uploadSuccess"
                                />
                            </template>
                            <template v-slot:form-item-content>
                                <wangEditor :content="data.content" @handleChange="handleChange" />
                            </template>
                        </form-page>
                    </div>
                    <template #footer>
                        <span>
                            <el-button size="small" @click="dialogForm.dialogVisible = false">取消</el-button>
                            <el-button size="small" type="primary" @click=" handleSubmit ">确认</el-button>
                        </span>
                    </template>
                </el-dialog>
            </el-col>
        </el-row>
    </div>
</template>

<script setup name="productPackage">
import myTable from "@/components/common/table.vue"
import searchForm from "@/components/common/searchForm.vue"
import imgUpload from "@/components/FileUpload/imgUpload.vue"
import formPage from "@/components/common/formPage.vue"
import wangEditor from "@/components/common/wangEditor/index.vue"
import {
    findMenuList, findArticleList, addArticle, delArticleById,
    updateArticle, findArticleDetail, updateState
} from "@/api/api";
import initRules from '@/utils/initRules'
import { mergeObjOfValue, deepClone } from '@/utils/index'
import { getTableData } from '@/mixins/mixins';
import { nextTick, onMounted, toRefs } from "vue";
const { proxy } = getCurrentInstance();
const columns = ref([
    {
        label: "ID",
        prop: "id"
    },
    {
        label: "标题",
        prop: "title"
    },
    {
        label: "作者",
        prop: "author"
    },
    {
        label: "封面图片",
        prop: "coverPic",
        slot: "coverPic"
    },
    {
        label: "菜单名字",
        prop: "menuName"
    },
    {
        label: "文章排序",
        prop: "sort"
    },
    {
        label: "阅读量",
        prop: "readCount"
    },
    {
        label: "分享数",
        prop: "shareCount"
    },
    {
        label: "状态",
        prop: "state",
        slot: "state"
    },
    {
        label: "操作",
        prop: "",
        width: 120,
        align: "left",
        slot: "operation"
    }
])
const menuList = ref([])
const searchItem = ref([])
const searchData = ref({
    menuId: "",
})
const dialogForm = ref({
    dialogVisible: false,
    title: '新增'
})
const formInfoData = {
    id: null,
    menuId: "",
    sort: "",
    title: "",
    author: "",
    coverPic: "",
    content: "",
    state: "",
    type: "0",
    readCount: "",
    shareCount: "",
}
const listTypeInfo = ref({
    menuList: menuList.value,
    stateList: [
        { label: '上架', value: '1' },
        { label: '下架', value: '0' }
    ],
    typeList: [
        { label: '是', value: '1' },
        { label: '否', value: '0' }
    ]
})
const formInfo = reactive({
    formRef: null,
    data: formInfoData,
    fieldList: [
        { label: '菜单名称', value: 'menuId', type: 'select', list: 'menuList', required: true },
        { label: '文章状态', value: 'state', type: 'radio', list: 'stateList', required: true },
        { label: '轮播图文章', value: 'type', type: 'radio', list: 'typeList', required: true },
        { label: '文章排序', value: 'sort', type: 'inputNumber', min: 0, required: true },
        { label: '文章标题', value: 'title', type: 'input', required: true },
        { label: '作者', value: 'author', type: 'input', required: true },
        { label: '阅读量', value: 'readCount', type: 'inputNumber', min: 0, required: true },
        { label: '分享数', value: 'shareCount', type: 'inputNumber', min: 0, required: true },
        { label: '封面图片', value: 'coverPic', slot: true, required: true },
        { label: '文章内容', value: 'content', slot: true, required: true },
    ],
    rules: {},
    labelWidth: '110px'
})
const { data, fieldList, rules, formRef } = toRefs(formInfo)
//hook
const {
    tableData,
    pagination,
    table_loading,
    init,
    handleSizeChange,
    handleDelete,
    currentChange,
} = getTableData(findArticleList, delArticleById)
// 生成表单验证
function handleInitRules () {
    rules.value = initRules(fieldList.value)
}
// 上传图片回调
function uploadSuccess (url) {
    data.value.coverPic = url
}
// 富文本编辑器
function handleChange (val) {
    data.value.content = val
}
// 上下架
function handleUpdateState (rowData) {
    let params = {
        id: rowData.id,
        state: rowData.state == 0 ? 1 : 0,
    }
    updateState(params).then((res) => {
        init(searchData.value)
    })
}
// 新增
function confirmAdd () {
    mergeObjOfValue(data.value, formInfoData)
    data.value.readCount = Math.floor(Math.random() * 500)
    data.value.shareCount = Math.floor(Math.random() * 500)
    dialogForm.value.title = '新增'
    dialogForm.value.dialogVisible = true
}
// 修改
function handleEdit (rowData) {
    findArticleDetail({ id: rowData.id }).then((res) => {
        mergeObjOfValue(data.value, res.data)
        data.value.menuId = rowData.menuId
        data.value.id = rowData.id
        data.value.state = data.value.state + ''
        data.value.type = data.value.type + ''
        dialogForm.value.title = '修改'
        dialogForm.value.dialogVisible = true
    })
}
// 提交
function handleSubmit () {
    formRef.value.validate((valid) => {
        if (valid) {
            if (dialogForm.value.title == '新增') {
                addArticle(data.value)
                    .then((res) => {
                        proxy.$modal.msgSuccess('新增成功')
                        dialogForm.value.dialogVisible = false
                        init(searchData.value)
                    })
                    .finally(() => { })
            } else {
                updateArticle(data.value)
                    .then((res) => {
                        proxy.$modal.msgSuccess('修改成功')
                        dialogForm.value.dialogVisible = false
                        init(searchData.value)
                    })
                    .finally(() => { })
            }
        }
    })
}
// 获取菜单id
async function handleFindMenuList () {
    await findMenuList(pagination.value).then((res) => {
        menuList.value = res.data.map((v) => {
            return { value: v.name, id: v.id }
        })
        listTypeInfo.value.menuList = res.data.map((v) => {
            return { label: v.name, value: v.id + '' }
        })
    })
}
function handleSearchItem () {
    searchItem.value = [
        {
            type: "input",
            label: "文章标题",
            prop: "title",
            placeholder: "请填写文章标题"
        },
        {
            type: "input",
            label: "作者",
            prop: "author",
            placeholder: "请填写作者"
        },
        {
            type: "select",
            label: "菜单id",
            prop: "menuId",
            selectList: menuList.value,
        },
        {
            type: "select",
            label: "状态",
            prop: "state",
            selectList: [
                { id: 1, value: '上架' },
                { id: 0, value: '下架' },
            ],
        },
        {
            type: "daterange",
            dateType: 'datetime',
            label: "时间",
            timeFormat: "YYYY-MM-DD HH:mm:ss",
            timeList: ["startTime", "endTime"]
        },
    ]
}
onMounted(async () => {
    data.value = deepClone(formInfoData)
    handleInitRules()
    await handleFindMenuList()
    init(searchData.value)
    handleSearchItem()
})
</script>
